package com.cloud.customtoastdemo.toast

import android.content.Context
import android.util.Log
import android.widget.Toast
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * @auth: njb
 * @date: 2024/10/20 2:38
 * @desc: 描述
 */
object ToastUtils {
    private var toastJob :Job ?= null
    private val TAG = "ToastUtils"
   fun Context.showToast(message: String, duration: Int = Toast.LENGTH_SHORT, delayTime: Long = 2000L) {
        val toast = Toast.makeText(this@showToast, message, duration)
        toast.show()

        // 只有在需要时才取消之前的延迟任务
        toastJob?.cancel()
        toastJob = CoroutineScope(Dispatchers.Main).launch {
            delay(delayTime)
            Log.d(TAG, "toast提示时间为$delayTime")
            toast.cancel()
        }
    }
}